#ifndef __M_FMT_H__
#define __M_FMT_H__

#include "util.hpp"
#include "message.hpp"
#include "level.hpp"
#include <memory>
#include <vector>
#include <tuple>

namespace maglog {

// 基础格式化项类，所有格式化子项继承自此类
class FormatItem {
    public:
        using ptr = std::shared_ptr<FormatItem>;
        virtual ~FormatItem() {}
        // 将日志消息格式化输出到指定的输出流中
        virtual void format(std::ostream &os, const LogMsg &msg) = 0;
};

// 消息格式化项，用于格式化日志的消息内容
class MsgFormatItem : public FormatItem {
    public:
        MsgFormatItem(const std::string &str = ""){}
        virtual void format(std::ostream &os, const LogMsg &msg) override {
            os << msg._payload;
        }
};

// 日志等级格式化项，用于格式化日志的等级
class LevelFormatItem : public FormatItem {
    public:
        LevelFormatItem(const std::string &str = ""){}
        virtual void format(std::ostream &os, const LogMsg &msg) override {
            os << LogLevel::toString(msg._level);
        }
};

// 日志名称格式化项，用于格式化日志的名称
class NameFormatItem : public FormatItem {
    public:
        NameFormatItem(const std::string &str = ""){}
        virtual void format(std::ostream &os, const LogMsg &msg) override {
            os << msg._name;
        }
};

// 线程ID格式化项，用于格式化日志的线程ID
class ThreadFormatItem : public FormatItem {
    public:
        ThreadFormatItem(const std::string &str = ""){}
        virtual void format(std::ostream &os, const LogMsg &msg) override {
            os << msg._tid;
        }
};

// 时间格式化项，用于格式化日志的时间戳
class TimeFormatItem : public FormatItem {
    private:
        std::string _format;
    public:
        TimeFormatItem(const std::string &format = "%H:%M:%S") : _format(format) {
            if (format.empty()) _format = "%H:%M:%S";
        }
        virtual void format(std::ostream &os, const LogMsg &msg) override {
            time_t t = msg._ctime;
            struct tm lt;
            localtime_r(&t, &lt);
            char tmp[128];
            strftime(tmp, 127, _format.c_str(), &lt);
            os << tmp;
        }
};

// 文件名格式化项，用于格式化日志的源文件名
class CFileFormatItem : public FormatItem {
    public:
        CFileFormatItem(const std::string &str = ""){}
        virtual void format(std::ostream &os, const LogMsg &msg) override {
            os << msg._file;
        }
};

// 行号格式化项，用于格式化日志的行号
class CLineFormatItem : public FormatItem {
    public:
        CLineFormatItem(const std::string &str = ""){}
        virtual void format(std::ostream &os, const LogMsg &msg) override {
            os << msg._line;
        }
};

// Tab格式化项，用于插入制表符
class TabFormatItem : public FormatItem {
    public:
        TabFormatItem(const std::string &str = ""){}
        virtual void format(std::ostream &os, const LogMsg &msg) override {
            os << "\t";
        }
};

// 换行格式化项，用于插入换行符
class NLineFormatItem : public FormatItem {
    public:
        NLineFormatItem(const std::string &str = ""){}
        virtual void format(std::ostream &os, const LogMsg &msg) override {
            os << "\n";
        }
};

// 其他格式化项，用于处理没有特殊格式化的字符
class OtherFormatItem : public FormatItem {
    private:
        std::string _str;
    public:
        OtherFormatItem(const std::string &str = "") : _str(str) {}
        virtual void format(std::ostream &os, const LogMsg &msg) override {
            os << _str;
        }
};

// 日志格式化器类，用于管理和应用日志格式化规则
class Formatter {
    public:
        using ptr = std::shared_ptr<Formatter>;

        // 构造函数：接受一个格式化模式字符串并解析
        Formatter(const std::string &pattern = "[%d{%H:%M:%S}][%t][%p][%c][%f:%l] %m%n")
            : _pattern(pattern) {
            assert(parsePattern());
        }

        // 获取格式化模式字符串
        const std::string pattern() { return _pattern; }

        // 对日志消息进行格式化，返回格式化后的字符串
        std::string format(const LogMsg &msg) {
            std::stringstream ss;
            for (auto &it : _items) {
                it->format(ss, msg);
            }
            return ss.str();
        }

        // 对日志消息进行格式化，并输出到指定的输出流中
        std::ostream& format(std::ostream &os, const LogMsg &msg) {
            for (auto &it : _items) {
                it->format(os, msg);
            }
            return os;
        }

        // 根据不同的格式化字符，创建一个格式化子项
        FormatItem::ptr createItem(const std::string &fc, const std::string &subfmt) {
            if (fc == "m") return FormatItem::ptr(new MsgFormatItem(subfmt));
            if (fc == "p") return FormatItem::ptr(new LevelFormatItem(subfmt));
            if (fc == "c") return FormatItem::ptr(new NameFormatItem(subfmt));
            if (fc == "t") return FormatItem::ptr(new ThreadFormatItem(subfmt));
            if (fc == "n") return FormatItem::ptr(new NLineFormatItem(subfmt));
            if (fc == "d") return FormatItem::ptr(new TimeFormatItem(subfmt));
            if (fc == "f") return FormatItem::ptr(new CFileFormatItem(subfmt));
            if (fc == "l") return FormatItem::ptr(new CLineFormatItem(subfmt));
            if (fc == "T") return FormatItem::ptr(new TabFormatItem(subfmt));
            return FormatItem::ptr();
        }

        // 解析格式化模式字符串
        bool parsePattern() {
            std::vector<std::tuple<std::string, std::string, int>> arry;
            std::string format_key;  // 存放%后的格式化字符
            std::string format_val;  // 存放格式化字符后面的子格式字符串
            std::string string_row;  // 存放原始的非格式化字符
            bool sub_format_error = false;
            int pos = 0;

            while (pos < _pattern.size()) {
                if (_pattern[pos] != '%') {
                    string_row.append(1, _pattern[pos++]);
                    continue;
                }
                if (pos + 1 < _pattern.size() && _pattern[pos + 1] == '%') {
                    string_row.append(1, '%');
                    pos += 2;
                    continue;
                }
                if (!string_row.empty()) {
                    arry.push_back(std::make_tuple(string_row, "", 0));
                    string_row.clear();
                }
                pos += 1;  // pos指向格式化字符位置
                if (pos < _pattern.size() && isalpha(_pattern[pos])) {
                    format_key = _pattern[pos];
                } else {
                    std::cout << &_pattern[pos - 1] << "位置附近格式错误！\n";
                    return false;
                }

                pos += 1;  // pos指向格式化字符的下一个位置，判断是否包含子格式
                if (pos < _pattern.size() && _pattern[pos] == '{') {
                    sub_format_error = true;
                    pos += 1;  // pos指向花括号内的字符
                    while (pos < _pattern.size()) {
                        if (_pattern[pos] == '}') {
                            sub_format_error = false;
                            pos += 1;  // pos指向花括号后的字符
                            break;
                        }
                        format_val.append(1, _pattern[pos++]);
                    }
                }
                arry.push_back(std::make_tuple(format_key, format_val, 1));
                format_key.clear();
                format_val.clear();
            }
            if (sub_format_error) {
                std::cout << "{}格式错误\n";
                return false;
            }
            if (!string_row.empty()) arry.push_back(std::make_tuple(string_row, "", 0));
            if (!format_key.empty()) arry.push_back(std::make_tuple(format_key, format_val, 1));

            for (auto &it : arry) {
                if (std::get<2>(it) == 0) {
                    FormatItem::ptr fi(new OtherFormatItem(std::get<0>(it)));
                    _items.push_back(fi);
                } else {
                    FormatItem::ptr fi = createItem(std::get<0>(it), std::get<1>(it));
                    if (fi == nullptr) {
                        std::cout << "没有对应的格式化字符: %" << std::get<0>(it) << std::endl;
                        return false;
                    }
                    _items.push_back(fi);
                }
            }
            return true;
        }

    private:
        std::string _pattern;                  // 格式化模式字符串
        std::vector<FormatItem::ptr> _items;   // 存储解析后的格式化子项
};

} // namespace maglog

#endif
